package com.example.cofeed.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ada.common.util.GlideImageLoader;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.example.cofeed.R;
import com.example.cofeed.activity.AttentionMoreActivity;
import com.example.cofeed.activity.LoginActivity;
import com.example.cofeed.activity.WebViewActivity;
import com.example.cofeed.adapter.ComplexViewMF;
import com.example.cofeed.adapter.HomeAdapter;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseFragment;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.Ad;
import com.example.cofeed.entity.Area;
import com.example.cofeed.entity.Article;
import com.example.cofeed.entity.CardBean;
import com.example.cofeed.entity.Home;
import com.example.cofeed.entity.IndexNumber;
import com.example.cofeed.entity.Navigator;
import com.example.cofeed.even.LoginEeven;
import com.example.cofeed.even.RefreshEven;
import com.gongwen.marqueen.MarqueeView;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class HomeListFragment extends BaseFragment implements OnRefreshLoadMoreListener {

    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.tab_sub)
    TabLayout mTabSub;
    @BindView(R.id.tv_sheng)
    TextView mTvSheng;
    @BindView(R.id.layout_sheng)
    RelativeLayout mLayoutSheng;

    private HomeAdapter mHomeAdapter;
    private Banner mBanner;

    //-1 推荐，-2 关注
    private int mCatid;

    private int mChid;
    private int mAreaid;
    private Home mHome;
    private List<Navigator> mSubList = new ArrayList<>();
    private View banner;
    private MarqueeView mMarqueeView;
    private ComplexViewMF mComplexViewMFAd;

    private boolean isRefresh;

    //    public static HomeListFragment newInstance(int catid, int chid) {
//        HomeListFragment fragment = new HomeListFragment();
//        Bundle bundle = new Bundle();
//        bundle.putInt("catid", catid);
//        bundle.putInt("chid", chid);
//        fragment.setArguments(bundle);
//        return fragment;
//
//    }
    public static HomeListFragment newInstance(Navigator navigator) {
        HomeListFragment fragment = new HomeListFragment();
        Bundle bundle = new Bundle();
//        bundle.putInt("catid", catid);
//        bundle.putInt("chid", chid);
        bundle.putSerializable("navigator", navigator);
        fragment.setArguments(bundle);
        return fragment;

    }

    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_list, container, false);
        return view;
    }

    boolean isLogin;
    Article mArticle;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if (getArguments() != null) {
//            mCatid = getArguments().getInt("catid");//41大豆
//            mChid = getArguments().getInt("chid");
//            if (mChid == 328) {
//                isZSTrue = true;
//            }

            Navigator navigator = (Navigator) getArguments().getSerializable("navigator");
            mCatid = navigator.catid;
            mChid = navigator.chid;
        }
    }

    public void updateArguments(Navigator navigator) {
        mCatid = navigator.catid;
        mChid = navigator.chid;

    }

    @Override
    protected void initData() {
        banner = getLayoutInflater().inflate(R.layout.include_banner, (ViewGroup) mRvList.getParent(), false);
        mBanner = banner.findViewById(R.id.banner);

        mRvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mHomeAdapter = new HomeAdapter(null);

        mRvList.setAdapter(mHomeAdapter);
        mHomeAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (adapter.getData().size() < position) {
                return;
            }
            mArticle = (Article) adapter.getData().get(position);
            if (mArticle == null) {
                return;
            }
            if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
                ActivityUtils.startActivity(LoginActivity.class);
                isLogin = true;
                return;
            }
            isLogin = false;
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra(IntentKeyConstant.ID, mArticle.id);
            intent.putExtra(IntentKeyConstant.URL, mArticle.urlpath);
            startActivityForResult(intent, 01);

        });
        mRefreshLayout.setOnRefreshLoadMoreListener(this);

        if (mCatid == -1 || mCatid == -2) {
            if (mCatid == -1) {

                banner.findViewById(R.id.layout_marquee).setVisibility(View.VISIBLE);
                mMarqueeView = banner.findViewById(R.id.marquee_view);
                mComplexViewMFAd = new ComplexViewMF(getActivity());

                mMarqueeView.setInAndOutAnim(R.anim.out_top, R.anim.in_bottom);
                mMarqueeView.setMarqueeFactory(mComplexViewMFAd);

//                getData(true);
                mRefreshLayout.autoRefresh();
            } else {
                if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
                    View view = getActivity().getLayoutInflater().inflate(R.layout.include_no_data, (ViewGroup) mRvList.getParent(), false);
                    view.setVisibility(View.VISIBLE);
                    TextView textView = view.findViewById(R.id.tv_title);
                    textView.setGravity(Gravity.CENTER);
                    textView.setText("暂未登录，无关注，点击登录");
                    textView.setCompoundDrawablePadding(getActivity().getResources().getDimensionPixelOffset(R.dimen.activity_horizontal_margin));
                    textView.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.box, 0, 0);
                    view.setOnClickListener(v -> ActivityUtils.startActivity(LoginActivity.class));
                    mHomeAdapter.setEmptyView(view);

                } else {
//                    getData(true);
                    mRefreshLayout.autoRefresh();

                }

            }

        } else {

            mTabSub.setTabMode(TabLayout.MODE_SCROLLABLE);
            ApiService.navigator_subnav(this, mCatid, mChid, new DialogCallback<LzyResponse<List<Navigator>>>(getActivity()) {
                @Override
                public void onSuccess(Response<LzyResponse<List<Navigator>>> response) {
                    mSubList.clear();
                    mSubList.addAll(response.body().data);
                    if (ObjectUtils.isNotEmpty(mSubList)) {
                        for (int i = 0; i < mSubList.size(); i++) {
                            Navigator navigator = mSubList.get(i);
                            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_tab_sub, mTabSub, false);
                            TextView title = view.findViewById(R.id.tv_title);
                            switch (navigator.title.length()) {
                                case 4:
                                    title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
                                    break;
                                case 5:
                                    title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
                                    break;
                                case 6:
                                    title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 8);
                                    break;
                                default:
                                    title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                                    break;
                            }
                            title.setText(navigator.title);

                            TabLayout.Tab tab = mTabSub.newTab().setCustomView(view);
                            tab.setTag(null);
                            tab.setTag(navigator);
                            mTabSub.addTab(tab, i == 0 ? true : false);
                            mTabSub.setForeground(null);
                        }
                        getView().findViewById(R.id.layout_tab).setVisibility(View.VISIBLE);
                    } else {
//                        getData(true);
                        mRefreshLayout.autoRefresh();

                        getView().findViewById(R.id.layout_tab).setVisibility(View.GONE);
                    }
                }

                @Override
                public void onError(Response<LzyResponse<List<Navigator>>> response) {
                    super.onError(response);
                    mRefreshLayout.autoRefresh();

                }
            });

            mTabSub.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    mList.clear();
                    mPage = 1;
                    mChid = mSubList.get(tab.getPosition()).chid;
                    mCatid = mSubList.get(tab.getPosition()).catid;
                    mAreaid = 0;
//                    getData(true);
                    initCustomOptionPicker();

                    mRefreshLayout.autoRefresh();

                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });
        }

        initCustomOptionPicker();

    }

    private List<Area> areaList = new ArrayList<>();
    OptionsPickerView<CardBean> pvCustomOptions;

    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局

        if (mCatid == -1 || mCatid == -2) {
            return;
        }
        ApiService.navigator_get_areas(this, mCatid, mChid, new DialogCallback<LzyResponse<List<Area>>>() {
            @Override
            public void onSuccess(Response<LzyResponse<List<Area>>> response) {
                if (ObjectUtils.isNotEmpty(response.body().data)) {
                    mLayoutSheng.setVisibility(View.VISIBLE);
                    ArrayList<CardBean> cardItem = new ArrayList<>();
                    areaList.clear();
                    areaList.addAll(response.body().data);
                    for (int i = 0; i < response.body().data.size(); i++) {
                        cardItem.add(new CardBean(i, response.body().data.get(i).name));
                    }

                    /**
                     * @description
                     *
                     * 注意事项：
                     * 自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
                     * 具体可参考demo 里面的两个自定义layout布局。
                     */
                    pvCustomOptions = new OptionsPickerBuilder(getActivity(), new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3, View v) {
                            //返回的分别是三个级别的选中位置

                            mCatid = areaList.get(options1).catid;
                            mChid = areaList.get(options1).chid;
                            mAreaid = areaList.get(options1).areaid;
                            String tx = cardItem.get(options1).getPickerViewText();
                            mTvSheng.setText(tx);

                            mRefreshLayout.autoRefresh();

//                            getData(false);
//                btn_CustomOptions.setText(tx);
                        }
                    })
                            .setTitleText("请选择地区")

                            .isDialog(false)
                            .build();

                    pvCustomOptions.setPicker(cardItem);//添加数据

                } else {
                    mLayoutSheng.setVisibility(View.GONE);
                }
            }
        });

    }

    protected void refreshData(Navigator navigator) {
        mCatid = navigator.catid;
        mChid = navigator.chid;
        mTabSub.setTabMode(TabLayout.MODE_SCROLLABLE);
        ApiService.navigator_subnav(this, mCatid, mChid, new DialogCallback<LzyResponse<List<Navigator>>>(getActivity()) {
            @Override
            public void onSuccess(Response<LzyResponse<List<Navigator>>> response) {
                mSubList.clear();
                mSubList.addAll(response.body().data);
                if (ObjectUtils.isNotEmpty(mSubList)) {
                    for (int i = 0; i < mSubList.size(); i++) {
                        Navigator navigator = mSubList.get(i);
                        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_tab_sub, mTabSub, false);
                        TextView title = view.findViewById(R.id.tv_title);
                        switch (navigator.title.length()) {
                            case 4:
                                title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
                                break;
                            case 5:
                                title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
                                break;
                            case 6:
                                title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 8);
                                break;
                            default:
                                title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                                break;
                        }
                        title.setText(navigator.title);

                        TabLayout.Tab tab = mTabSub.newTab().setCustomView(view);
                        tab.setTag(null);
                        tab.setTag(navigator);
                        mTabSub.addTab(tab, i == 0 ? true : false);
                        mTabSub.setForeground(null);
                    }
                    getView().findViewById(R.id.layout_tab).setVisibility(View.VISIBLE);
                } else {
//                        getData(true);
                    mRefreshLayout.autoRefresh();

                    getView().findViewById(R.id.layout_tab).setVisibility(View.GONE);
                }
            }
        });

    }

    private int mPage = 1;
    private List<Article> mList = new ArrayList<>();

    private void getData(boolean isFirst) {
        if (mCatid == -1 || mCatid == -2) {
            //推荐
            if (mCatid == -1) {

                ApiService.index_number("index_number", new DialogCallback<LzyResponse<List<IndexNumber>>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<IndexNumber>>> response) {
                        mComplexViewMFAd.setData(response.body().data);
                        mMarqueeView.startFlipping();
                    }
                });

                String refresh = "";
                if (!isFirst  && isRefresh){
                    refresh = "new";
                }
                ApiService.dataset_recommend("dataset_recommend", mPage, refresh, new DialogCallback<LzyResponse<Home>>(isFirst ? getActivity() : null) {
                    @Override
                    public void onSuccess(Response<LzyResponse<Home>> response) {
                        mHome = response.body().data;
                        if (mPage == 1) {
                            List<String> images = new ArrayList<>();
                            if (ObjectUtils.isNotEmpty(response.body().data.ad)) {
                                if (mHomeAdapter.getHeaderLayoutCount() == 0) {
                                    mHomeAdapter.addHeaderView(banner);
                                }

                                for (Ad ad : response.body().data.ad) {
                                    images.add(ad.img);
                                }
                                mBanner.setImages(images).setImageLoader(new GlideImageLoader()).start();
                                mBanner.setOnBannerListener(new OnBannerListener() {
                                    @Override
                                    public void OnBannerClick(int position) {
                                        Ad ad = response.body().data.ad.get(position);
                                        if (ObjectUtils.isEmpty(ad.url)){
                                            return;
                                        }
                                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                                        intent.putExtra(IntentKeyConstant.TYPE, 9);
                                        intent.putExtra(IntentKeyConstant.URL, ad.url);
                                        startActivity(intent);

                                    }
                                });
                            }
                        }

                        if (ObjectUtils.isNotEmpty(response.body().data.article_list)) {

                            if (ObjectUtils.isNotEmpty(response.body().data.rcm) && ObjectUtils.isNotEmpty(response.body().data.rcm.rcm)) {
                                response.body().data.rcm.type = 1;
                                int shownum;
                                if (response.body().data.article_list.size() < response.body().data.rcm.shownum) {
                                    shownum = response.body().data.article_list.size();
                                } else {
                                    shownum = response.body().data.rcm.shownum;
                                }

                                response.body().data.article_list.add(shownum, response.body().data.rcm);

                            }
                            mList.addAll(response.body().data.article_list);

                            mPage++;
                        }
                        mHomeAdapter.setNewData(mList);
                        finishRefresh(mRefreshLayout);
                        isRefresh = true;


                    }

                    @Override
                    public void onError(Response<LzyResponse<Home>> response) {
                        super.onError(response);
                        finishRefresh(mRefreshLayout);

                    }
                });

            }
            //关注
            else {
                if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
                    finishRefresh(mRefreshLayout);
                    return;
                }

                Map<String, Object> follow_param = new HashMap<>();

                follow_param.put("page", mPage);
                String refresh = "";
                if (!isFirst  && isRefresh){
                    refresh = "new";
                }

                ApiService.dataset_follow(this, refresh, follow_param, new DialogCallback<LzyResponse<Home>>(isFirst ? getActivity() : null) {
                    @Override
                    public void onSuccess(Response<LzyResponse<Home>> response) {
                        mHome = response.body().data;
                        if (mPage == 1) {
                            if (mHome == null || ObjectUtils.isEmpty(mHome.article_list)) {
                                View view = getActivity().getLayoutInflater().inflate(R.layout.include_guanzhu_empty, (ViewGroup) mRvList.getParent(), false);
                                view.findViewById(R.id.tv_goguanzhu).setOnClickListener(v -> {
                                    ActivityUtils.startActivity(AttentionMoreActivity.class);
                                });
                                mHomeAdapter.setEmptyView(view);
                                finishRefresh(mRefreshLayout);

                                return;
                            }

                            getView().findViewById(R.id.layout_guanzhu).setVisibility(View.VISIBLE);
                            getView().findViewById(R.id.layout_guanzhu).setOnClickListener(v -> {
                                ActivityUtils.startActivity(AttentionMoreActivity.class);
                            });
                            mHomeAdapter.setNoLine(true);

                            List<String> images = new ArrayList<>();
                            if (ObjectUtils.isNotEmpty(response.body().data.ad)) {
                                banner.findViewById(R.id.layout_marquee).setVisibility(View.GONE);

                                for (Ad ad : response.body().data.ad) {
                                    images.add(ad.img);
                                }
                                mBanner.setImages(images).setImageLoader(new GlideImageLoader()).start();
                                if (mHomeAdapter.getHeaderLayoutCount() == 0) {
                                    mHomeAdapter.addHeaderView(banner);
                                }
                            }
                        }

                        if (ObjectUtils.isNotEmpty(response.body().data.article_list)) {
                            if (ObjectUtils.isNotEmpty(response.body().data.rcm) && ObjectUtils.isNotEmpty(response.body().data.rcm.rcm)) {
                                response.body().data.rcm.type = 1;
                                int shownum;
                                if (response.body().data.article_list.size() < response.body().data.rcm.shownum) {
                                    shownum = response.body().data.article_list.size();
                                } else {
                                    shownum = response.body().data.rcm.shownum;
                                }
                                response.body().data.article_list.add(shownum, response.body().data.rcm);

                            }
                            mPage++;
                            mList.addAll(response.body().data.article_list);
                        }
                        finishRefresh(mRefreshLayout);
                        mHomeAdapter.setNewData(mList);
                        isRefresh = true;

                    }

                    @Override
                    public void onError(Response<LzyResponse<Home>> response) {
                        super.onError(response);
                        finishRefresh(mRefreshLayout);
                    }
                });
            }

        } else {
            Map<String, Object> ad_param = new HashMap<>();
            Map<String, Object> article_list_param = new HashMap<>();
            Map<String, Object> rcm_param = new HashMap<>();

            ad_param.put("catid", mCatid);

            article_list_param.put("page", mPage);
            article_list_param.put("catid", mCatid);
            article_list_param.put("chid", mChid);
            article_list_param.put("areaid", mAreaid);

            rcm_param.put("catid", mCatid);

            ApiService.dataset_homepage(this, ad_param, article_list_param, rcm_param, new DialogCallback<LzyResponse<Home>>(isFirst ? getActivity() : null) {
                @Override
                public void onSuccess(Response<LzyResponse<Home>> response) {
                    mHome = response.body().data;
                    if (mPage == 1) {
                        List<String> images = new ArrayList<>();
                        if (ObjectUtils.isNotEmpty(response.body().data.ad)) {
                            if (mHomeAdapter.getHeaderLayoutCount() == 0) {
                                mHomeAdapter.addHeaderView(banner);
                            }

                            banner.findViewById(R.id.layout_marquee).setVisibility(View.GONE);

                            for (Ad ad : response.body().data.ad) {
                                images.add(ad.img);
                            }
                            mBanner.setImages(images).setImageLoader(new GlideImageLoader()).start();

                        }
                    }

                    int shownum;

                    if (ObjectUtils.isNotEmpty(response.body().data.article_list)) {
                        if (ObjectUtils.isNotEmpty(response.body().data.rcm) && ObjectUtils.isNotEmpty(response.body().data.rcm.rcm)) {
                            response.body().data.rcm.type = 1;
                            if (response.body().data.article_list.size() < response.body().data.rcm.shownum) {
                                shownum = response.body().data.article_list.size();
                            } else {
                                shownum = response.body().data.rcm.shownum;
                            }
                            response.body().data.article_list.add(shownum, response.body().data.rcm);
                        }

                        if (mPage == 1 && mChid == 328) {
                            Article article = new Article();
                            article.type = 2;
                            if (ObjectUtils.isEmpty(response.body().data.article_list)) {
                                response.body().data.article_list.add(0, article);
                            } else if (response.body().data.article_list.size() < 3) {
                                response.body().data.article_list.add(response.body().data.article_list.size() + 1, article);
                            } else {
                                response.body().data.article_list.add(3, article);
                            }
                        }

                        mPage++;
                        mList.addAll(response.body().data.article_list);
                    }

                    mHomeAdapter.setNewData(mList);
                    finishRefresh(mRefreshLayout);

                }

                @Override
                public void onError(Response<LzyResponse<Home>> response) {
                    super.onError(response);
                    finishRefresh(mRefreshLayout);
                }
            });
        }

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getData(false);

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (mHomeAdapter.getHeaderLayoutCount() > 0) {
            mHomeAdapter.removeHeaderView(banner);
        }
        mHomeAdapter.notifyDataSetChanged();
        mPage = 1;
        mList.clear();
        getData(false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(RefreshEven refreshEven) {
        if (refreshEven.type == 0) {
            mRefreshLayout.autoRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(LoginEeven loginEeven) {
        if (isLogin && ObjectUtils.isNotEmpty(mArticle)) {
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra(IntentKeyConstant.ID, mArticle.id);
            intent.putExtra(IntentKeyConstant.URL, mArticle.urlpath);
            startActivityForResult(intent, 01);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mCatid = 0;
        mChid = 0;
    }

    @OnClick(R.id.layout_sheng)
    public void onViewClicked() {
//        initCustomOptionPicker();
        if (pvCustomOptions != null) {
            pvCustomOptions.show();

        }

    }
}
